package com.woniu.filter;


import com.woniu.config.MyAuthenticationFailureHandler;
import com.woniu.exception.TokenInvalidAuthenticationException;
import com.woniu.exception.TokenIsNullAuthenticationException;
import com.woniu.outlet.dao.UserPoMapper;
import com.woniu.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private UserPoMapper userMapper;
    @Autowired
    private MyAuthenticationFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获得客户端请求的头信息 -->Token值
        String strToken = request.getHeader("tokenStr");
        //判断当前请求是否是/login,/login.html
        String uri = request.getRequestURI().toString();
        if (uri.equals("/login")) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        if (StringUtils.isEmpty(strToken)) {

            //处理token为空的情形
            failureHandler.onAuthenticationFailure(request, response,
                    new TokenIsNullAuthenticationException("Token为空!"));

        }
        try {
            //检查token是否有效
            if (JwtTokenUtil.checkSign(strToken)) {
                //token有效
                String username = JwtTokenUtil.getUserId(strToken);
                //根据用户名查询数据库跟标识符信息
                List<String> perCodes = userMapper.selectPercodeByPerm(username);
                List<GrantedAuthority> authorities = new ArrayList<>();
                perCodes.forEach(perCode -> {
                    authorities.add(new SimpleGrantedAuthority(perCode));
                });
                //封装一个认证通过的AuthenticationToken -密码设为空
                Authentication authentication =
                        new UsernamePasswordAuthenticationToken(username,"", authorities);
                //存放security上下文
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //放行
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            failureHandler.onAuthenticationFailure(request, response,
                    new TokenInvalidAuthenticationException("Token无效!"));
            e.printStackTrace();
        }


    }
}
